﻿using SlimDX.Direct3D11;
using SlimDX.DXGI;

namespace JamesZhao.Engine.Graphics.Surfaces
{
    public class DepthSurface : Surface
    {
        private DepthStencilView _depthView;

        public DepthSurface(GraphicsDevice device, TextureTargetMode mode)
        {
            Device = device;
            Mode = mode;
            WidthRatio = HeightRatio = 1;
        }

        public DepthStencilView DepthView
        {
            get { return _depthView ?? (_depthView = new DepthStencilView(Device.Device, Texture)); }
        }


        public override void Initialize()
        {
            if (Mode == TextureTargetMode.Raw) return;

            DestroyTexture();
            DestroyViews();

            Texture = new Texture2D(Device.Device, new Texture2DDescription
                                                       {
                                                           ArraySize = 1,
                                                           BindFlags = BindFlags.DepthStencil,
                                                           CpuAccessFlags = CpuAccessFlags.None,
                                                           Format = Format.D24_UNorm_S8_UInt,
                                                           Width = ActualSize.Width,
                                                           Height = ActualSize.Height,
                                                           MipLevels = 1,
                                                           OptionFlags = ResourceOptionFlags.None,
                                                           SampleDescription = SampleDescription,
                                                           Usage = ResourceUsage.Default
                                                       });
        }

        public override void DestroyTexture()
        {
            if (Texture != null)
            {
                Texture.Dispose();
            }
            Texture = null;
        }

        public override void DestroyViews()
        {
            if (_depthView != null)
                _depthView.Dispose();
            _depthView = null;
        }

        public void DestroyResources()
        {
            DestroyTexture();
            DestroyViews();
        }
    }
}